<?php

	class convert_orderControl extends BaseMemberControl {
		static $store_id = 6;

		var $data;


		public function __construct() {
			if ($_GET['op'] == 'index' || $_GET['op'] == 'getorderstatus') {
				return;
			}
			parent::__construct();
			Language::read('member_member_index');
		}

		/**
		 * 查询订单状态
		 */
		public function getOrderStatusOp() {
			$data = array();

			$rules = [
				'userName'        => '用户名',
				'userPass'        => '用户密码',
				"sign"            => '校验码',
				'orderSn'         => '订单号',
			];


			unset($_GET['act']);
			unset($_GET['op']);

			foreach ($_GET as $key => $val) {
				if ($key != 'userPass') {
					$val = trim(urldecode($val));
				}
				$data[$key] = urldecode(htmlspecialchars_decode($val));
			}

			foreach ($rules as $key => $val) {
				if (!isset($data[$key]) || empty($val)) {
					$this->show_message(-1, "{$val}不能为空");
				}
			}

			//校验sign
			unset($data['sign']);

			ksort($data);
			$str = array();
			foreach ($data as $key => $val) {
				$str[] = "{$key}={$val}";
			}
			$str = implode("&", $str);
			if (urldecode($_GET['sign']) != md5($str)) {
				$this->show_message(-2, "校验码不正确");
			}

//			$this->data = $data;

			//校验用户名和密码是否正确
			$auth_condition = array(
				'member_name' => $data['userName'],
				'member_passwd' => md5($data['userPass'])
			);
			$minfo = Model('member')->where($auth_condition)->find();
			if (!$minfo || $minfo['allow_push'] != 1) {
				$this->show_message(-3, "用户名或密码错误");
			}

			//查询订单
			$search_condition = [
				'order_sn' => $data['orderSn'],
			];
			if (true) {
				$search_condition['member_id'] = $minfo['member_id'];
			}
			$oinfo = Model()->table('out_order')->where($search_condition)->find();

			if (!$oinfo) {
				$this->show_message(1, "没有找到该订单");
			}

			$oinfo = Model()->table('order')->where([
				'out_order' => $oinfo['id'],
			])->find();
			if (!$oinfo) {
				$this->show_message(1, "没有找到该订单");
			}


			$status = [
				'10' => "STATUS_WAITING_FOR_PAYMENT",
				'20' => "STATUS_WAITING_TO_SEND",
				'30' => 'STATUS_WAITING_TO_BUYER_ACCEPT',
				'40' => 'STATUS_FINISHED'
			];
			$resp_data = [];
			if ($oinfo['order_state'] > 20) {
				$resp_data['shippingCode'] = $oinfo['shipping_code'];
				$ominfo = Model()->table("order_common")->where([
					'order_id' => $oinfo['order_id'],
				])->find();
				$exp = Model()->table('express')->find($ominfo['shipping_express_id']);
				if (!$exp) {
					$resp_data['shippingCompany'] = "未知物流公司";
					$resp_data['shippingCompanyCode'] = "NULL";
				}
				else{
					$resp_data['shippingCompany'] = $exp['e_name'];
					$resp_data['shippingCompanyCode'] = $exp['e_code'];
				}
			}

			$status = isset($status[$oinfo['order_state']]) ? $status[$oinfo['order_state']] : 'STATUS_UNKNOWN';
			$this->show_message(0,$status,$resp_data);

		}

		public function indexOp() {
			$rules = array(
				'buyerName'       => '购买人姓名',
				'buyerMobile'     => '购买人手机号码',
				'orderSn'         => '订单号',
				'payAmount'       => '支付金额',
				'payType'         => '支付方式',
				'payTime'         => '支付时间',
				'paySn'           => '支付单号',
				'consignee'       => '收货人姓名',
				'idNumber'        => '收货人身份证号码',
				'address'         => '收货地址',
				'provinceCode'    => '省级代号',
				"cityCode"        => "市级代号",
				"areaCode"        => "区域代号",
				'consigneeMobile' => '收货人手机号码',
				'orderGoods'      => '商品详情',
				'userName'        => '用户名',
				'userPass'        => '用户密码',
				"sign"            => '校验码',
			);

			$data = array();

			foreach ($_POST as $key => $val) {
				if ($key != 'userPass') {
					$val = trim(urldecode($val));
				}
				$data[$key] = urldecode(htmlspecialchars_decode($val));
			}

			foreach ($rules as $key => $val) {
				if (!isset($data[$key]) || empty($val)) {
					$this->show_message(-1, "{$val}不能为空");
				}
			}

			//校验sign
			unset($data['sign']);

			ksort($data);
			$str = array();
			foreach ($data as $key => $val) {
				$str[] = "{$key}={$val}";
			}
			$str = implode("&", $str);
			if (urldecode($_POST['sign']) != md5($str)) {
				$this->show_message(-2, "校验码不正确");
			}

			$this->data = $data;

			//校验用户名和密码是否正确
			$minfo = Model('member')->where(array('member_name' => $data['userName'], 'member_passwd' => $data['userPass']))->find();
			if (!$minfo || $minfo['allow_push'] != 1) {
				$this->show_message(-3, "用户名或密码错误");
			}

			//校验支付金额
			$data['payAmount'] = number_format($data['payAmount'], 2);
			if ($data['payAmount'] <= 0) {
				$this->show_message(-4, "支付金额不正确");
			}

			//校验手机号
			$reg = "/^1[345789][0-9]{9}$/";
			if (!preg_match($reg, $data['buyerMobile'])) {
				$this->show_message(-5, "购买人手机号码格式错误");
			}
			if (!preg_match($reg, $data['consigneeMobile'])) {
				$this->show_message(-5, "收货人手机号码格式错误");
			}

			//支付时间
			if (strlen($data['payTime']) != 10 || $data['payTime'] < strtotime('1970-1-1')) {
				$this->show_message(-6, "支付时间错误");
			}

			//代号
			$area_code = array();
			foreach (array('provinceCode', 'cityCode', 'areaCode') as $key => $val) {
				$area_info = Model('area')->where(array('area_code' => $data[$val], 'area_deep' => $key + 1))->find();
				if (!$area_info) {
					$this->show_message(-7, $rules[$val] . '错误');
				} else {
					$area_code[] = $area_info['area_code'];
				}
			}

			//idcard
			if (!preg_match("/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/", $data['idNumber'])) {
				$this->show_message(-8, "身份证号格式错误");
			}

			$order_goods = null;
			try {
				$order_goods = json_decode($data['orderGoods'], true);
			} catch (Exception $e) {
				$this->show_message(-9, "订单商品格式不对");
			}

			$goods_amount = 0;
			$order_tax = 0;
			foreach ($order_goods as $key => $goods) {
				if (!isset($goods['price']) || !isset($goods['num']) || !isset($goods['goodsId'])) {
					$this->show_message(-9, "订单商品格式不对");
				}
				if ($goods['num'] <= 0 || $goods['price'] <= 0) {
					$this->show_message(-9, "订单商品格式不对");
				}
				//检索商品在我们库中是否存在
				$ginfo = Model()->table('goods')->where(array('goods_id' => $goods['goodsId']))->find();
				$gminfo = Model()->table('goods_common')->where(array('goods_commonid' => $ginfo['goods_commonid']))->find();
				$ginfo['goods_costprice'] = $gminfo['goods_costprice'];

				if (!$ginfo) {
					$this->show_message(-10, "商品不存在");
				}

				if ($ginfo['goods_storage'] < $goods['num']) {
					$this->show_message(-11, $ginfo['goods_name'] . " 库存不足");
				}

				if ($gminfo['open_tax'] != 1) {
					$this->show_message(-12, $ginfo['goods_name'] . ' 不是保税商品');
				}

				$tax = $this->cal_tax_ex($ginfo);
				$order_tax += $tax * $goods['num'];
				$goods_amount += ($ginfo['goods_costprice'] + $tax) * $goods['num'];
			}


			$out_order = Model('out_order')->where(array('member_id' => $minfo['member_id'], 'order_sn' => $data['orderSn']))->find();
			if (count($out_order)) {
				$this->show_message(3, "该订单已推送过");
			}
			$out_id = Model('out_order')->insert(array(
				'member_id'  => $minfo['member_id'],
				'order_sn'   => $data['orderSn'],
				'order_info' => serialize($data),

			));
			if (!$out_id) {
				$this->show_message(4, "订单保存失败");
			}

			//做成UUID
			$admin_sinfo = Model('store')->where(array('store_id' => self::$store_id))->find();
//        print_r($admin_sinfo);
			$insert_data = array(
				'order_sn'         => $this->get_uuid(),
				'pay_sn'           => $this->get_uuid(),
				'store_id'         => self::$store_id,
				'store_name'       => $admin_sinfo['store_name'],
				'buyer_id'         => $minfo['member_id'],
				'buyer_name'       => $minfo['member_name'],
				'buyer_email'      => $minfo['member_email'],
				'add_time'         => time(),
				'payment_code'     => '',
				'payment_time'     => '',
				'finnshed_time'    => '',
				'goods_amount'     => $goods_amount,
				'order_amount'     => $goods_amount,
				'rcb_amount'       => 0,
				'pd_amount'        => '',
				'shipping_fee'     => 0,
				'evaluation_state' => 0,
				'order_state'      => 10,
				'refund_state'     => 0,
				'lock_state'       => 0,
				'delete_state'     => 0,
				'refund_amount'    => 0,
				'delay_time'       => 0,
				'order_from'       => 1,
				'shipping_code'    => '',
				'margin'           => 0,
				'is_tax_order'     => 1,
				'phone'            => $data['consigneeMobile'],
				'address'          => $data['address'],
				'idcard'           => $data['idNumber'],
				'receiver_name'    => $data['consignee'],
				'order_tax'        => $order_tax,
				'out_order'        => $out_id
			);


			$order_id = Model()->table('order')->insert($insert_data);

			if (!$order_id) {
				Model()->table('out_order')->where(['id' => $out_id])->delete();
				$this->show_message(1, '订单插入失败');
			}

			$receiver_info = array(
				'phone'     => $data['consigneeMobile'],
				'mob_phone' => $data['consigneeMobile'],
				'tel_phone' => '',
				'address'   => $data['address'],
				'area'      => $data['address'],
				'street'    => ''
			);
			$order_common = array(
				'order_id'            => $order_id,
				'store_id'            => self::$store_id,
				'shipping_time'       => '',
				'shipping_express_id' => 0,
				'evaluation_time'     => 0,
				'evalseller_state'    => 0,
				'evalseller_time'     => 0,
				'order_message'       => 0,
				'order_pointscount'   => 0,
				'voucher_price'       => 0,
				'voucher_code'        => '',
				'deliver_explain'     => '',
				'daddress_id'         => 0,
				'reciver_name'        => $data['consignee'],
				'reciver_info'        => serialize($receiver_info),
				'reciver_province_id' => $area_code[0],
				'reciver_city_id'     => $area_code[1],
				'reciver_area_id'     => $area_code[2],
				'invoice_info'        => '',
				'phone'               => $data['consigneeMobile'],
				'idcard'              => $data['idNumber'],
				'address'             => $data['address']
			);

			$id = Model()->table('order_common')->insert($order_common);
			if (!$id) {
				Model('order')->where(array('order_id' => $order_id))->delete();
				Model()->table('out_order')->where(['id' => $out_id])->delete();
				$this->show_message(1, "订单插入失败");
			}

			foreach ($order_goods as $key => $goods) {
				$ginfo = Model()->table('goods')->where(array('goods_id' => $goods['goodsId']))->find();
				$gminfo = Model()->table('goods_common')->where(array('goods_commonid' => $ginfo['goods_commonid']))->find();
				$ginfo['goods_costprice'] = $gminfo['goods_costprice'];
				$arr = array(
					'order_id'        => $order_id,
					'goods_id'        => $ginfo['goods_id'],
					'goods_name'      => $ginfo['goods_name'],
					'goods_price'     => $ginfo['goods_costprice'],
					'goods_num'       => $goods['num'],
					'goods_image'     => $ginfo['goods_image'],
					'goods_pay_price' => $ginfo['goods_costprice'],
					'store_id'        => 1,
					'buyer_id'        => $minfo['member_id'],
					'goods_type'      => 1,
					'promotions_id'   => 0,
					'commis_rate'     => 0,
					'gc_id'           => $ginfo['gc_id'],
					'tax'             => $this->cal_tax_ex($ginfo),
					'source_price'    => $ginfo['goods_costprice'],
					'goods_proxy'     => $ginfo['goods_costprice']
				);
				if (!Model('order_goods')->insert($arr)) {
					Model()->table('out_order')->where(['id' => $out_id])->delete();
					Model('order')->where(array('order_id' => $order_id))->delete();
					Model('order_common')->where(array('order_id' => $order_id))->delete();
					Model('order_goods')->where(array('order_id' => $order_id))->delete();
					$this->show_message(2, "订单商品错误");
				}
			}

			$id = Model('order_pay')->insert(array(
				'pay_sn'        => $insert_data['pay_sn'],
				'buyer_id'      => $minfo['member_id'],
				'api_pay_state' => 0
			));

			if (!$id) {
				$this->show_message(5, "插入订单支付表失败");
			}

			$this->show_message(0, "推送成功");
		}

		public function show_message($errcode, $errmsg,$errdata = null) {
			$arr = array(
				'errCode'    => $errcode,
				'errMessage' => $errmsg,
			);
			if ($errdata) {
				$arr['data'] = $errdata;
			}
			header("Content-type:text/html;charset=utf-8");
			echo json_encode($arr,JSON_UNESCAPED_UNICODE);

			exit;
		}

		public function get_uuid() {
			while (true) {
				$order_sn = date('YmdHis') . rand(10000, 99999);
				$oinfo = Model('order')->where(array('order_sn' => $order_sn))->find();
				if (!$oinfo) {
					return $order_sn;
				}
			}
		}

		public function cal_tax_ex($goods) {

			$model_setting = Model('setting');
			$config = $model_setting->getListSetting();

			if ($config['open_tax'] == 1 && $goods['open_tax'] == 1) {
				$exten_info = Model('goods_common')->find($goods['goods_commonid']);
				$tax = preg_replace_callback("/{\s*(\w+)\s*}/", function ($matched) use (&$goods, $exten_info) {

					$goods['goods_costprice'] = empty($exten_info['goods_costprice']) ? 0 : $exten_info['goods_costprice'];
					switch ($matched[1]) {
						case 'source_price':
						case 'goods_price':
							return $goods['goods_costprice'];
						case 'rate':
							return $exten_info['tax'];
						default:
							return 0;
					}
				}, $config['tax_formula']);

				eval('$tax = ' . $tax . ';');
				return $tax;
			}
			return 0;
		}

		public function import_excelOp() {
			$path = dirname(BASE_PATH) . '/static/webuploader/' . $_GET['excel_path'];
			require_once dirname(BASE_PATH) . '/static/lib/PHPExcel.php';
			if (!file_exists($path)) {
				echo 'failed';
				exit;
			}

			$objReader = PHPExcel_IOFactory::createReaderForFile($path);
			$objPHPExcel = $objReader->load($path);
			/**
			 * @var $sheet PHPExcel_Worksheet
			 */
			$sheet = $objPHPExcel->getSheet(0);

			$list = array(
				'buyerName',
				'buyerMobile',
				'orderSn',
				'payAmount',
				'payType',
				'payTime',
				'paySn',
				'consignee',
				'idNumber',
				'address',
				'provinceCode',
				'cityCode',
				'areaCode',
				'consigneeMobile',
				'goodsId',
				'price',
				'num',
			);

			$highestRow = $sheet->getHighestRow(); // 取得总行数
			$highestColumm = $sheet->getHighestColumn(); // 取得总列数


			/** 循环读取每个单元格的数据 */
			$data = array();
			$temp = array('orderGoods' => array());
			for ($row = 2; $row <= $highestRow; $row++) {//行数是以第1行开始
				for ($column = 'A', $count = 0; $column <= $highestColumm; $column++, $count++) {//列数是以A列开始
					$val = $sheet->getCell($column . $row)->getValue();
					//如果该行为空，那么直接给上一行的orderGoods补充数据
					if ($column == 'A' && empty($val)) {
						$oval = $sheet->getCell('O' . $row)->getValue();
						if (empty($oval)) {
							break;
						}
						$orderGoods = &$data[count($data) - 1]['orderGoods'];
						$orderGoods[] = array(
							'goodsId' => $sheet->getCell('O' . $row)->getValue(),
							'price'   => $sheet->getCell('P' . $row)->getValue(),
							'num'     => $sheet->getCell('Q' . $row)->getValue(),
						);
						break;
					}
					if ($column == 'O') {
						$temp['orderGoods'] = array(
							array(
								'goodsId' => $sheet->getCell('O' . $row)->getValue(),
								'price'   => $sheet->getCell('P' . $row)->getValue(),
								'num'     => $sheet->getCell('Q' . $row)->getValue(),
							)
						);
						if (count($temp)) {
							$data[] = $temp;
							$temp = array('orderGoods' => array());
						}
						continue;
					} else {
						$temp[$list[$count]] = $val;
					}
				}


			}

			$ret = array();

			$minfo = Model('member')->where(array('member_id' => $_SESSION['member_id']))->find();
			foreach ($data as $item) {
				$item['userName'] = $minfo['member_name'];
				$item['userPass'] = $minfo['member_passwd'];
				$item['orderGoods'] = json_encode($item['orderGoods']);
				$item['sign'] = $this->sign($item);
				$url = "http://" . $_SERVER['HTTP_HOST'] . '/shop/?act=convert_order';
				$result = $this->post_get($url, $item);
				if ($result['errCode'] != 0) {
					$ret[] = array(
						'sn'  => $item['orderSn'],
						'msg' => $result['errMessage']
					);
				}
			}

			@unlink($path);

			echo json_encode($ret);
			exit;
		}

		private function post_get($url, $param = null, $decode = true) {
			$option = array(
				'http' => array(
					'method'        => 'POST',
					'ignore_errors' => true,
					'header'        => "Content-type: application/x-www-form-urlencoded ",
				),
			);
			if ($param) {
				$option['http']['content'] = http_build_query($param);
			}
			$context = stream_context_create($option);

			// Send the request
			$response = file_get_contents($url, false, $context);
//        $response = str_replace(':}', ':""}', $response);
//        $response = str_replace(':,', ':"",', $response);



			if (!$decode) {
				return $response;
			}

			return json_decode($response, true);

		}

		private function sign($arr) {
			ksort($arr);
			$str = array();
			foreach ($arr as $key => $val) {
				$str[] = "{$key}={$val}";
			}
			$str = implode('&', $str);
			return md5($str);
		}


		public function listOp() {
			$model_order = Model('order');

			//搜索
			$condition = array();
			$condition['buyer_id'] = $_SESSION['member_id'];
			if ($_GET['order_sn'] != '') {
				$condition['order_sn'] = $_GET['order_sn'];
			}
			$if_start_date = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $_GET['query_start_date']);
			$if_end_date = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $_GET['query_end_date']);
			$start_unixtime = $if_start_date ? strtotime($_GET['query_start_date']) : null;
			$end_unixtime = $if_end_date ? strtotime($_GET['query_end_date']) : null;
			if ($start_unixtime || $end_unixtime) {
				$condition['add_time'] = array('time', array($start_unixtime, $end_unixtime));
			}
			if ($_GET['state_type'] != '') {
				$condition['order_state'] = str_replace(
					array('state_new', 'state_pay', 'state_send', 'state_success', 'state_noeval', 'state_cancel'),
					array(ORDER_STATE_NEW, ORDER_STATE_PAY, ORDER_STATE_SEND, ORDER_STATE_SUCCESS, ORDER_STATE_SUCCESS, ORDER_STATE_CANCEL), $_GET['state_type']);
			}
			if ($_GET['state_type'] == 'state_noeval') {
				$condition['evaluation_state'] = 0;
				$condition['order_state'] = ORDER_STATE_SUCCESS;
			}

			//回收站
			if ($_GET['recycle']) {
				$condition['delete_state'] = 1;
			} else {
				$condition['delete_state'] = 0;
			}

			$condition['out_order'] = array('gt', '0');

			$order_list = $model_order->getOrderList($condition, 20, '*', 'order_id desc', '', array('order_common', 'order_goods', 'store'));

			$model_refund_return = Model('refund_return');
			$order_list = $model_refund_return->getGoodsRefundList($order_list);

			//订单列表以支付单pay_sn分组显示
			$order_group_list = array();
			$order_pay_sn_array = array();
			foreach ($order_list as $order_id => $order) {

				//显示取消订单
				$order['if_cancel'] = $model_order->getOrderOperateState('buyer_cancel', $order);

				//显示退款取消订单
				$order['if_refund_cancel'] = $model_order->getOrderOperateState('refund_cancel', $order);

				//显示投诉
				$order['if_complain'] = $model_order->getOrderOperateState('complain', $order);

				//显示收货
				$order['if_receive'] = $model_order->getOrderOperateState('receive', $order);

				//显示锁定中
				$order['if_lock'] = $model_order->getOrderOperateState('lock', $order);

				//显示物流跟踪
				$order['if_deliver'] = $model_order->getOrderOperateState('deliver', $order);

				//显示评价
				$order['if_evaluation'] = $model_order->getOrderOperateState('evaluation', $order);

				//显示删除订单(放入回收站)
				$order['if_delete'] = $model_order->getOrderOperateState('delete', $order);

				//显示永久删除
				$order['if_drop'] = $model_order->getOrderOperateState('drop', $order);

				//显示还原订单
				$order['if_restore'] = $model_order->getOrderOperateState('restore', $order);

				foreach ($order['extend_order_goods'] as $value) {
					$value['image_60_url'] = thumb($value, 60, $value['store_id']);
					$value['image_240_url'] = thumb($value, 240, $value['store_id']);
					$value['goods_type_cn'] = orderGoodsType($value['goods_type']);
					$value['goods_url'] = urlShop('goods', 'index', array('goods_id' => $value['goods_id']));
					if ($value['goods_type'] == 5) {
						$order['zengpin_list'][] = $value;
					} else {
						$order['goods_list'][] = $value;
					}
				}

				if (empty($order['zengpin_list'])) {
					$order['goods_count'] = count($order['goods_list']);
				} else {
					$order['goods_count'] = count($order['goods_list']) + 1;
				}
				$order_group_list[$order['pay_sn']]['order_list'][] = $order;

				//如果有在线支付且未付款的订单则显示合并付款链接
				if ($order['order_state'] == ORDER_STATE_NEW) {
					$order_group_list[$order['pay_sn']]['pay_amount'] += $order['order_amount'] - $order['pd_amount'] - $order['rcb_amount'];
				}
				$order_group_list[$order['pay_sn']]['add_time'] = $order['add_time'];

				//记录一下pay_sn，后面需要查询支付单表
				$order_pay_sn_array[] = $order['pay_sn'];
			}

			//取得这些订单下的支付单列表
			$condition = array('pay_sn' => array('in', array_unique($order_pay_sn_array)));
			$order_pay_list = $model_order->getOrderPayList($condition, '', '*', '', 'pay_sn');
			foreach ($order_group_list as $pay_sn => $pay_info) {
				$order_group_list[$pay_sn]['pay_info'] = $order_pay_list[$pay_sn];
			}
			Tpl::output('order_group_list', $order_group_list);
			Tpl::output('order_pay_list', $order_pay_list);
			Tpl::output('show_page', $model_order->showpage());

//        self::profile_menu($_GET['recycle'] ? 'member_order_recycle' : 'member_order');

			Tpl::showpage("co.list");
		}

		public function manual_addOp() {
			Tpl::showpage("co.add");
		}

		public function get_next_areaOp() {
			$id = $_GET['id'];
			if ($id == 'undefined') {
				echo json_encode(array());
			}
			echo json_encode(Model('area')->where(array('area_parent_id' => $id))->select());
		}

		public function manual_submitOp() {
			$param = $_POST;
			$arr = array();
			foreach ($_POST['goodsId'] as $k => $v) {
				$arr[] = array(
					'goodsId' => $v,
					'price' => $_POST['price'][$k],
					'num' => $_POST['num'][$k]
				);
			}
			$param['orderGoods'] = json_encode($arr);
			unset($param['goodsId']);
			unset($param['price']);
			unset($param['num']);
			$param['payTime'] = strtotime($param['payTime']);
			$minfo = Model('member')->where(array('member_id' => $_SESSION['member_id']))->find();
			$param['userName'] = $minfo['member_name'];
			$param['userPass'] = $minfo['member_passwd'];
			$param['sign'] = $this->sign($param);
			$url = "http://" . $_SERVER['HTTP_HOST'] . '/shop/?act=convert_order';
			$result = $this->post_get($url, $param);
			echo $result['errMessage'];
			exit;
		}
	}
